package com.yinxing.framework.shiro.filter;

import com.yinxing.framework.shiro.exception.RequiresPermissionException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * 当前用户必须拥有相应权限
 * 判断条件:subject.isPermittedAll(perms)
 */
public class RequiresPermissionsFilter extends PermissionsAuthorizationFilter {

    private final static String PERMS_KEY = RequiresPermissionsFilter.class.getName() + "." + "PERMS_KEY";

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

        Subject subject = getSubject(request, response);
        String[] perms = (String[]) mappedValue;

        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }

        request.setAttribute(PERMS_KEY, perms);

        return isPermitted;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        String[] perms = (String[]) request.getAttribute(PERMS_KEY);
        String msg = "用户不具备所需权限" + Arrays.toString(perms);
        throw new RequiresPermissionException(msg);
    }
}
